<?php
/**
* This is the FQDN Class. This class is used to work with the actual domain, and set properties
* about the FQDN. This class is used to control how Bind works with the domain. It doesn't do anything
* with the hosts for the actual domain.
*
* $Id: FQDN.class.php 49 2005-08-04 04:50:34Z vluther $ 				
* @package includes
* @version $Rev: 49 $
* @copyright Copyright &copy; 2000-2007, Linuxpowered, Inc               
* @author Vidyut Luther <vid@linuxpowered.com> 
**/

class FQDN {

    /**
     * Domain Id 
     *
     * @var int
     */
    var $_intId  ; 
    var $_strOwner ; 
    var $_strFqdn ; 
    /**
     * The TTL in seconds for the Domain
     *
     * @var string
     */
    var $_intTtl; 
    /**
     * Serial for the domain name 
     *
     * @var integer
     */
    var $_intSerial ; 
    /**
     * Refresh rate in Minutes/Hours or Seconds
     *
     * @var string
     */
    var $_strRefresh ; 
    /**
     * Retry Rate , usually in Minutes (Appended by M)
     *
     * @var string
     */
    var $_strRetry ; 
    var $_strExpiry ;  
    var $_strMinimum ; 
    /**
     * SOA for the Domain
     *
     * @var string
     */
    var $_strSoa ; 
    /**
     * Default IP for the Domain 
     *
     * @var string
     */
    var $strDefaultIp ; 
    var $serverGroup; 
/**
 * FQDN : The constructor, everything is set to NULL; 
 * @param $ : 
 * 
 * @return boolean
 * @access public
 **/
    function FQDN() 
    {
        $this->_intId = null ;
        $this->_intSerial = null ; 
        $this->_intTtl = null ; 
        $this->_strExpiry = null ; 
        $this->_strFqdn = null ; 
        $this->_strMinimum = null;  
        $this->db =& new DB();  
        return true; 
    }

/**
 * mLoad: Loads all the properties of a FQDN loads an array of domains if no specific id is set. 
 * 
 * @return bool
 * @access public
 **/
    function mLoad()
    {
        if(!is_null($this->_intId)) {
            require_once(INCLUDE_PATH."/DB.php") ; 
            $db = new DB(); 
            $sql = "select * from fqdn where fqdnid = '". $this->_intId ."'"; 
           
            $rs = $db->mRun($sql) ;
            while($row = mysql_fetch_assoc($rs)) {
                $this->mSetOwner($row['user']) ; 
                $this->mSetFqdn($row['fqdn']); 
                $this->mSetTtl($row['ttl']) ; 
                $this->mSetSerial($row['serial']) ;
                $this->mSetRefresh($row['refresh']) ; 
                $this->mSetRetry($row['retry']) ; 
                $this->mSetExpiry($row['expiry']); 
                $this->mSetMinimum($row['minimum']) ; 
                $this->mSetSOA($row['soa']); 
                $this->mSetDefaultIp($row['defaultip']) ;  
                $this->setServerGroup($row['server_group']); 
            }
        } else {
            $this->ErrorMsg = "Cannot Load a Proper Domain Yet ! "; 
            return false; 
        } 
      return true;         
    }
    
   
   function setServerGroup($groupid)
   {
     $this->serverGroup = $groupid ; 
   }
   
   function getServerGroup() 
   {
     return $this->serverGroup; 
   }
    
     
    /**
     * Method to Add a fqdn for a specific user. Takes defaults from binder_config to set default values per domain, this used to rely on constants
     * in the global.inc.php, but this is no longer needed as the settings are stored in the database. Eventually, this may allow additional paramaters
     * like specific defaults for specific set of domains. But that requires changes to useradd, and domainadd, and a bunch of UI changes. 
     *
     * @param int $user 
     * @param string $fqdn
     */
    function mAddDomain($user,$fqdn,$group)
    {
      require_once(INCLUDE_PATH."/DB.php") ; 
      $db = new DB(); 
			$sql = "SELECT default_mx,default_ip,soa_ttl,soa_serial,soa_refresh,soa_retry,soa_expire,soa_mname,soa_cache FROM binder_config "; 
  
      $rs = $db->mRun($sql); 
      while($row = mysql_fetch_assoc($rs)) {
      	$defaultip = $row['default_ip']; 
        $defaultmx = $row['default_mx']; 
				$ttl = $row['soa_ttl']; 
      	$soa = $row['soa_mname']; 
				$soa_rname = $row['soa_rname']; 
      	$refresh = $row['soa_refresh']; 
      	$retry  = $row['soa_retry']; 
      	$expiry = $row['soa_expire']; 
      	$minimum = $row['soa_cache']; 
      }

      $fqdn = strtolower($fqdn); 
      if(!empty($group)) { 
        $defaultip = $this->groupDefaultIP($group);    
      }
      $serial = $this->generateSerial(); 
    
      echo "<Br> Adding : <b> $fqdn </b> <br> ";  
     
      $sql = "INSERT INTO fqdn (fqdn,ttl,user,serial,refresh,retry,expiry,minimum,soa,defaultip,server_group)
        VALUES ('$fqdn','$ttl','$user','$serial','$refresh','$retry','$expiry','$minimum','$soa','$defaultip','$group')";
    
    
      // If the domain add works, then go ahead and fill out the basic stubb for the domain
      // immediately. Otherwise display error message.  
      if($db->mInsert($sql)) {
        $fqdnid = mysql_insert_id();         
        $this->domainStub($fqdnid,$fqdn,$defaultmx,$defaultip) ; 
      } else { 
        echo "<br> There was a problem adding the domain <br> $sql <br> <strong> ";
        echo $db->strError . "</strong> <BR> "; 
        die; 
      }
      
      return true; 
    }

/**
 * generateSerial: This will generate a serial for the domain, as recommended by dnsreport.com 
 * The format will be: YYYYMMDDnn
 * @return int 
 * @access public
 **/
   
    
    function generateSerial()
    {
      $serial = date("Ymd");  
      $serial = $serial . rand(10,20); 
      return $serial ;  
    }
   

/**
 * groupDefaultIP : Get the default IP of a specific group. 
 * @param $group : int (Group Id) 
 * 
 * @return : int 
 * @access : private 
 **/
  function groupDefaultIP($group) 
  {
    $sql = "SELECT INET_NTOA(default_ip) AS default_ip FROM server_groups WHERE group_id='$group'"; 
    $rs = $this->db->mRun($sql); 
    while($row=mysql_fetch_assoc($rs)) { 
      $default_ip = $row['default_ip']; 
    }

    return $default_ip; 
  
  }

  function domainStub($fqdnid,$fqdn,$defaultmx,$defaultip)
  {
    require_once INCLUDE_PATH . '/Records.class.php'; 
    $objRecords =& new DNSRecord(); 
    // Add Default IP Record (*) 

    $sqlWWW = "INSERT INTO records (rtype,hostname,hostip,fqdnid) VALUES ('A','www',INET_ATON('$defaultip'),'$fqdnid')"; 
    $this->db->mRun($sqlWWW);

    $sqlFTP = "INSERT INTO records (rtype,hostname,hostip,fqdnid) VALUES ('A','ftp',INET_ATON('$defaultip'),'$fqdnid')"; 
    $this->db->mRun($sqlFTP);


    $sqlMX = "INSERT INTO records (rtype,hostname,hostip,fqdnid) VALUES ('MX','','$defaultmx','$fqdnid')"; 

    $this->db->mRun($sqlMX); 
    if(!$this->db->strError) {
      return true; 
    } else {
      return false; 
    }





  }




    function mSetId($id) 
    {
        $this->_intId = $id; 
        return true; 
    }


    function mSetOwner($strOwner)
    {
        $this->_strOwner = $strOwner ; 
        return true; 
    }
    
    
    function mSetFqdn($fqdn)
    {
        $this->_strFqdn = $fqdn ; 
        return true; 
    }

    function mSetTtl($ttl)
    {
        $this->_intTtl = $ttl ; 
        return true; 
    }

    function mSetSerial($serial) 
    {
        $this->_intSerial = $serial ; 
    }

    function mSetRefresh($refresh) 
    {
        $this->_strRefresh = $refresh; 
    } 

    function mSetRetry($retry) 
    {
        $this->_strRetry = $retry;
    }

    function mSetExpiry($expiry) 
    {
        $this->_strExpiry = $expiry ; 
    }

    function mSetMinimum($min) 
    {
        $this->_strMinimum = $min ; 
    }

    function mSetSOA($soa)
    {
        $this->_strSoa = $soa ; 
    }


    function mSetDefaultIp($defaultip)
    {
        $this->_strDefaultIp = $defaultip; 
    } 
   
    
    function getId()
    {
    	return $this->_intId; 
    }
    
    
    function getOwner()
    {
    	return $this->_strOwner; 
    }
    
    /**
     * Return the FQDN name,
     * @example : example.com
     * @access public 
     * @return string
     */
    function getFqdn()
    {
    	return $this->_strFqdn; 
    }
    
    
    function getTTL()
    {
    	return $this->_intTtl; 
    }
    
    function getSerial()
    {
    	return $this->_intSerial; 
    }

    function getRefresh()
    {
    	return $this->_strRefresh; 
    }
   
    function getRetry()
    {
    	return $this->_strRetry; 
    }
    
    
    /**
     * Returns the FQDN Expiry Time 
     * @access public 
     * @return string
     */
    function getExpiry()
    {
    	return $this->_strExpiry; 
    }
    
    function getMinimum()
    {
    	return $this->_strMinimum ; 
    }
   
    function getSOA()
    {
    	return $this->_strSoa;
    }
    
    /**
     * Returns the default IP for the FQDN
     *
     * @access public 
     * @return string
     */
    function getDefaultIp()
    {
    	return $this->_strDefaultIp; 
    }  
    

   
    /**
     * Loads all domains by order of domain name. 
     * 
     * Returns an array of all the domains, and all the properties of said domains. Use Sparingly.
     * @return array
     */
    function loadAllDomains()
    {
     $sql = "SELECT * from fqdn ORDER BY fqdn"; 
     require_once(INCLUDE_PATH."/DB.php") ; 
     $db = new DB();
     $rs = $db->mRun($sql);
     
     while($row=mysql_fetch_assoc($rs)) {
        $arrFqdn[] = $row ; 
     }
      
     return $arrFqdn;  
      
    }
  
    /*
      Get a List of domains, either by the user id, or just get an entire list of domains
    */
  
  
   
    function fqdnList($user=null,$searchval=null)
    {
  
      if(!is_null($searchval)) {
        $where = "AND fqdn LIKE '%$searchval%'"; 
      }
      
      if(!is_null($user)) {
      	$where = "AND f.user='$user' "; 
      }

      
      if(is_null($this->owner)) {
        $sql = "SELECT f.fqdn,f.defaultip,f.fqdnid,f.ttl,f.serial,f.soa,u.firstname,u.lastname,u.userid FROM fqdn f, users u WHERE f.user=u.userid $where ORDER BY u.userid, f.fqdn";       
      } else {
        $sql = "SELECT f.fqdn,f.defaultip,f.fqdnid,f.ttl,f.serial,f.soa,u.firstname,u.lastname FROM fqdn f, users u WHERE f.user=u.userid 
          AND f.user='". $this->owner ."' ORDER BY f.fqdn"; 
      }

      
      require_once(INCLUDE_PATH."/DB.php") ; 
      $db = new DB(); 
      
      $rs = $db->mRun($sql); 

      while($row=mysql_fetch_assoc($rs)) {
        $arrFqdn[] = $row ; 
      }
      
      return $arrFqdn;  


    }
    
  
    function removeDomain($domid)
    {
      $sql = "DELETE FROM fqdn WHERE fqdnid='$domid'"; 
      require_once(INCLUDE_PATH."/DB.php") ; 
      $db = new DB(); 
      
      if($db->Execute($sql,$type="DELETE")) {
        return true; 
      } else {
        return false; 
      }
      
    }

    
    function modifyDomain($post) 
    {
    	require_once(INCLUDE_PATH.'/DB.php');

    	$db = new DB(); 
    	$fqdnid = $post['fqdnid']; 
    	$defaultip = trim($post['default_ip']); 
    	$ttl = trim($post['soa_ttl']); 
    	$soa = trim($post['soa_mname']); 
    	$serial = trim($post['soa_serial']); 
    	$refresh = trim($post['soa_refresh']); 
    	$retry = trim($post['soa_retry']); 
    	$expire = trim($post['soa_expire']); 
    	$min = trim($post['soa_cache']); 
      $group = trim($post['domain_group']); 	
      $cascade = trim($post['cascade_group']); 


     if($cascade == "on") {
        echo "<div class=\"main\"> Group Changes are being Cascaded to all records </div>";
        $sqlips = "SELECT INET_NTOA(default_ip) AS default_ip, default_mx FROM server_groups WHERE group_id='$group'"; 
        $rs = $db->mRun($sqlips); 

        while($row=mysql_fetch_assoc($rs)) {
          $defaultip = $row['default_ip'] ; 
          $default_mx = $row['default_mx']; 
        }

        $this->cascadeGroup($group,$fqdnid); 
        
      } 


    	$sql = "UPDATE fqdn SET defaultip='$defaultip',soa='$soa',minimum='$min',expiry='$expire',retry='$retry',refresh='$refresh',serial='$serial',ttl='$ttl', server_group='$group' WHERE fqdnid='$fqdnid'"; 
    	
    	
    	#$rs = $db->mRun($sql); 
 			$rs = $db->mInsert($sql);   	

       	if(!$rs) {
    		echo "<br>There was a problem " . mysql_error() . "<br> "; 
    		die; 
    	} else {
    		return true; 
    	}
    }


  function cascadeGroup($group,$fqdn) 
  {
     $sql = "SELECT default_ip, default_mx,INET_NTOA(default_ip) AS realip FROM server_groups WHERE group_id='$group'"; 
     $rs= $this->db->mRun($sql); 
    
     while($row=mysql_fetch_assoc($rs)) {
       $defaultip = $row['default_ip'] ; 
       $default_mx = $row['default_mx'];
       $realip = $row['realip']; 
     }

    
    $updAsql = "UPDATE records SET hostip='$defaultip' WHERE fqdnid='$fqdn' AND rtype='A'"; 
    $this->db->mRun($updAsql); 
    if(!empty($default_mx)) {
      $updMXsql = "UPDATE records set hostip='$default_mx' WHERE fqdnid='$fqdn' AND rtype='MX'"; 
      $this->db->mRun($updAsql);
    }
 
    $updfqdn = "UPDATE fqdn set defaultip = '$realip' WHERE fqdnid='$fqdn' "; 
    
    $this->db->mRun($updfqdn); 

    

    return true; 
  }


  function cascadeIP($fqdn,$newip)
  {
    $sql = "UPDATE records set hostip='$newip' WHERE fqdnid='$fqdn' AND rtype='A'"; 
    $this->db->mRun($sql);
    
    $updfqdn = "UPDATE fqdn set defaultip = INET_NTOA('$newip') WHERE fqdnid='$fqdn' ";  
    $this->db->mRun($updfqdn); 
  }
    

/**
 * loadDomainsFor: Loads domain for a specific user. 
 * Returns domains owned by the user in alphabetical order. 
 * @param $user: The user for which to load domain for
 * 
 * @return : array 
 * @access : public
 **/
  function loadDomainsFor($userid)
  {
    $sql = "SELECT fqdnid,fqdn from fqdn where user='$userid' ORDER BY fqdn";
    $rs = $this->db->mRun($sql) ; 
    $fqdns = array(); 
    while($row=mysql_fetch_array($rs)) {
        $myfqdns[$row[0]] = $row[1] ; 
    }
    
    return $myfqdns; 

  }


/**
 * groupList: Returns an array of groups for a specific user, or all users if the user is an admin
 * @param $curuser: 
 * @param $searchval: 
 * 
 * @return 
 * @access 
 **/
  function groupOptions($curuser,$curgroup="0")
  {
    $sql =  "SELECT group_id,group_name FROM server_groups WHERE group_owner = '$curuser' ORDER BY group_name";
    $rs = $this->db->mRun($sql);
    
    while($row=mysql_fetch_assoc($rs)) {
      if($curgroup == $row['group_id']) {
        $selected = "SELECTED"; 
      } else {
        $selected = ''; 
      }
      $groupOptions .= "<option value='" . $row['group_id'] . "' $selected> " . $row['group_name'] . "</option> "; 
    }

    return $groupOptions; 
  }



  }


?>
